package com.hcms.admin.security;

import cn.hutool.json.JSONUtil;
import com.hcms.common.api.CommonResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 用户登录失败
 */
@Component
public class AdminAuthenticationFailureHandler implements AuthenticationFailureHandler {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        logger.error("Run onAuthenticationFailure()");
        logger.info("The account or password is incorrect");
        CommonResponse<Object> result = new CommonResponse<>(HttpStatus.BAD_REQUEST,"账号或密码错误");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Cache-Control", "no-cache");
        response.setStatus(result.getStatus());
        response.getWriter().println(JSONUtil.toJsonStr(result));
        response.getWriter().flush();
        response.getWriter().close();
    }

}
